import { Body, Controller, Post, Req, UsePipes } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { MerchantModelService } from 'src/model/merchant-model/merchant-model.service';
import dtoValidationPipe from 'src/pipe/Dto.pipe';
import { RedisService } from 'src/redis/redis.service';
import { LoginDto } from './dto';
import { LoginService } from './login.service';
import * as dayjs from 'dayjs'
import { errorReturn, successReturn } from 'src/utils';
const crypto = require('crypto')

@Controller('login')
export class LoginController {
    constructor(
        private service:LoginService,
        private config:ConfigService,
        private redisService:RedisService
        //private merchant:MerchantModelService
    ) {}

    @Post()
    @UsePipes(dtoValidationPipe())
    async login(@Body() dto:LoginDto) {
        const { merchant, account, password } = dto
        let time = dayjs().unix()
        let nextDayTime = dayjs(dayjs().format('YYYY-MM-DD')).add(1, 'day').unix() //下一天整点
        let roleType:RoleType
        let lockKey = ''
        let loginCountKey = ''
        let keyPre = ''

        if(merchant === this.config.get<string>('platformLoginName')) {
            keyPre = 'pl'
            roleType = 0
        }else {
            keyPre = 'm' + ':' + (crypto.createHash('md5').update(dto.merchant).digest('hex'))
            roleType = 1
        }

        const loginFailMaxCount = this.config.get<number>('loginFailMacCount')
        loginCountKey = keyPre + ':lg:er:' + account + ':' + dayjs().format('YYMD')
        let loginCount = Number((await this.redisService.get(loginCountKey)) || 0)
        if(loginCount >= loginFailMaxCount) return errorReturn(`今天登录失败次数超过${loginFailMaxCount}次，禁止今天再登录`)

        lockKey = keyPre + account

        const lock = await this.redisService.store.set(lockKey,'', {NX : true, EX : 10})
        if(!lock) return errorReturn()

        try {
            const res = await this.service.login(dto, roleType)
            if(res) {
                this.redisService.del(loginCountKey) //清空登录次数
                return successReturn(res)
            }else {
                this.redisService.set(loginCountKey, loginCount + 1, {EX : nextDayTime - time})
            }
        } catch (error) {
            
        }finally {
            this.redisService.del(lockKey)
        }

        return errorReturn('登录账号或密码错误')

    }

    @Post('refresh')
    async refresh(@Body('token') token:string, @Req() {roleTye, adminId, merchantId}) {
        if(!token) return
        return this.service.refresh(adminId || merchantId, roleTye, token)
    }
}
